package org.qpcr.community.device.entity;

import cn.hutool.json.JSONUtil;
import lombok.Data;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Data
public class CalibrationData implements Externalizable {

    private static final long serialVersionUID = 1L;

    /**
     * 请求ID
     */
    private String requestId;

    /**
     * 设备ID
     */
    private String deviceId;

    /**
     * 模块代码
     */
    private String moduleCode;

    /**
     * 校准类型
     */
    private String calibrationType;

    /**
     * 校准参数
     */
    private Map<String, Object> parameters;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 状态
     */
    private String status;

    /**
     * 消息
     */
    private String message;

    public CalibrationData() {
        this.createTime = LocalDateTime.now();
        this.parameters = new HashMap<>();
        this.status = "PENDING";
    }

    public CalibrationData(String deviceId, String moduleCode) {
        this();
        this.deviceId = deviceId;
        this.moduleCode = moduleCode;
        this.requestId = generateRequestId();
    }

    private String generateRequestId() {
        return "CAL_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(requestId != null ? requestId : "");
        out.writeUTF(deviceId != null ? deviceId : "");
        out.writeUTF(moduleCode != null ? moduleCode : "");
        out.writeUTF(calibrationType != null ? calibrationType : "");
        out.writeObject(parameters);
        out.writeObject(createTime);
        out.writeUTF(status != null ? status : "");
        out.writeUTF(message != null ? message : "");
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        requestId = in.readUTF();
        deviceId = in.readUTF();
        moduleCode = in.readUTF();
        calibrationType = in.readUTF();
        parameters = (Map<String, Object>) in.readObject();
        createTime = (LocalDateTime) in.readObject();
        status = in.readUTF();
        message = in.readUTF();
    }

    public String toJsonString() {
        // 使用FastJSON确保中文字符正确编码
        return com.alibaba.fastjson.JSON.toJSONString(this,
            com.alibaba.fastjson.serializer.SerializerFeature.WriteMapNullValue,
            com.alibaba.fastjson.serializer.SerializerFeature.WriteNullStringAsEmpty,
            com.alibaba.fastjson.serializer.SerializerFeature.WriteNonStringValueAsString);
    }
}